<?php

namespace app\controller\api;

use app\controller\ApiBaseController;
use app\WxCommon;

class Wx extends ApiBaseController
{
    /**
     * 接收微信消息
     *
     * @return void
     */
    public function receive()
    {
        try {
            //接收参数
            $strSign = param_filter($this->request->param('signature', ''), 'string');
            $strTimestamp = param_filter($this->request->param('timestamp', ''), 'string');
            $strNonce = param_filter($this->request->param('nonce', ''), 'string');
            $strEchoStr = param_filter($this->request->param('echostr', ''), 'string');
            $strRes = $strTimestamp . $strNonce . env('WECHAT_TOKEN');
            $strNewSign = sha1($strRes);
            if ($strSign == $strNewSign) {
                echo $strEchoStr;
                die;
            }
            echo 'error';
            die;
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage(), $e->getCode());
        }
    }


    public function encrypt()
    {
        try {
            //接收参数
            $strMsgSign = param_filter($this->request->param('msg_signature', ''), 'string');
            $strTimestamp = param_filter($this->request->param('timestamp', ''), 'string');
            $strNonce = param_filter($this->request->param('nonce', ''), 'string');
            $strEncrypt = param_filter($this->request->param('Encrypt', ''), 'string');

            //验证签名
            $boolVerfySign = WxCommon::verifySign($strMsgSign, $strTimestamp, $strNonce, $strEncrypt);
            if (!$boolVerfySign) {
                return api_response([], '签名验证失败', 0);
            }

            //解密消息
            $arrData = WxCommon::decryptMsg($strEncrypt);
            if (empty($arrData)) {
                return api_response([], '解密失败', 0);
            }
            return api_response($arrData, '解密成功', 1);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage(), $e->getCode());
        }
    }
}
